#include "marqueeview.h"
#include <QHBoxLayout>
#include <QApplication>
#include <QMouseEvent>
#include <QBitmap>
#include "common.h"

int MarqueeView::m_id = qRegisterMetaType<MarqueeView*>();

MarqueeView::MarqueeView(QWidget *parent)
    :ViewObject(parent)
    ,m_indexCurrent(-1)
    ,m_changeLabelshow(false)
    ,m_timer(NULL)
    ,m_label(NULL)
    ,m_movie(NULL)
    ,m_marqueeViewParam(NULL)
{
    setAttribute(Qt::WA_DeleteOnClose);
    m_label = new QLabel(this);
    m_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(m_label, 0, Qt::AlignCenter);
    layout->setContentsMargins(0, 0, 0, 0);
    setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
    {
        m_objectParam = new ParamObject;
    }

    if (m_marqueeViewParam == NULL)
    {
        m_marqueeViewParam = new MarqueeViewParam;
    }

    if(m_timer == NULL)
    {
        m_timer = new QTimer(this);
        connect(m_timer, SIGNAL(timeout()), this, SLOT(TimeOutSlot()));
    }
}


MarqueeView::~MarqueeView()
{
}

void MarqueeView::ShowObject(QWidget* parent, QString filename, QString prefix, ProtocolData *ptr_data)
{
    Q_UNUSED(ptr_data);
    if(m_marqueeViewParam == NULL || m_objectParam == NULL)
    {
        return;
    }

    setParent(parent);
    m_label->clear();

    if(m_marqueeViewParam->m_positionInfo !="" &&
       m_marqueeViewParam->m_startIndex != -1 &&
       m_marqueeViewParam->m_endIndex != -1)
    {
        m_mapPosition.clear();
        QString pos = m_marqueeViewParam->m_positionInfo;
        QStringList posStrList = pos.split(";");
//        LOG_QDEBUG<<__FUNCTION__<<posStrList.size();
        for(int i = 0; i<posStrList.size()-1; i++)
        {
//            LOG_QDEBUG<<__FUNCTION__<<i;
            QStringList rec = posStrList[i].split(",");
            PositionInfo info;
            info.w = rec[0].toInt();
            info.h = rec[1].toInt();
            info.x = rec[2].toInt();
            info.y = rec[3].toInt();
            m_mapPosition[i] = info;
        }
        m_timer->start(m_marqueeViewParam->m_timeMS);
    }

    QString url = m_marqueeViewParam->m_res;
#ifdef __linux__
    mPrefix = prefix;
#else
    Q_UNUSED(prefix);
    mPrefix = QString("%1/res/img/").arg(myapp::mDynamicMapParam->m_project_path);
#endif

    if(url != "")
    {
        url.push_front(mPrefix);
        url =  url.right(1) == ";" ? url.left(url.size() - 1) : url;
        if("gif" == url.right(3))
        {
            if(NULL == m_movie)
            {
                m_movie = new QMovie(url, QByteArray(), this);
                if(NULL == m_movie)
                    return;
            }
            else
            {
                m_movie->stop();
            }
            m_movie->setFileName(url);
            m_movie->start();
            QRect rect = m_movie->frameRect();
            m_movie->setScaledSize(QSize(rect.width(), rect.height()));
            m_label->setMovie(m_movie);
            m_objectParam->SetWidth(rect.width());
            m_objectParam->SetHeight(rect.height());
#ifndef __linux__
            emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
#endif
        }
        else
        {
            QPixmap pixmap(url);
            m_objectParam->SetWidth(pixmap.width());
            m_objectParam->SetHeight(pixmap.height());
            m_label->setPixmap(pixmap);
            emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
        }
    }
    else
    {
        m_label->setText(m_objectParam->GetObjectName());
    }

    location(m_objectParam->GetX(), m_objectParam->GetY(),
                m_objectParam->GetWidth(), m_objectParam->GetHeight());
    m_label->setFixedSize(size());

    show();
}

void MarqueeView::HideObject()
{
    setParent(NULL);
    if(m_timer!= NULL)
    {
        m_timer->stop();
    }
    if(m_movie!=NULL)
    {
        m_movie->stop();
    }
    hide();
}

void MarqueeView::DestoryObject()
{
    HideObject();

    if(m_marqueeViewParam != NULL)
    {
        delete m_marqueeViewParam;
        m_marqueeViewParam = NULL;
    }

    if (m_objectParam != NULL)
    {
        delete m_objectParam;
        m_objectParam = NULL;
    }
    close();
}

void MarqueeView::GetAttribute(std::string& attribute)
{
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();
    base["idtype"] = m_objectParam->GetStIdType().toStdString();

    base["time_ms"] = QString::number(m_marqueeViewParam->m_timeMS).toStdString();
    base["startIndex"] = QString::number(m_marqueeViewParam->m_startIndex).toStdString();
    base["endIndex"] = QString::number(m_marqueeViewParam->m_endIndex).toStdString();
    base["positioninfo"] = m_marqueeViewParam->m_positionInfo.toStdString();
    base["url"] = m_marqueeViewParam->m_res.toStdString();
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void MarqueeView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if(CheckJsonValueType(root, "zindex", Json::stringValue))
    {
        m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }

    if(CheckJsonValueType(root, "stid", Json::stringValue))
    {
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"x", Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"y", Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }

    if(CheckJsonValueType(root, "w", Json::stringValue))
    {
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }

    if(CheckJsonValueType(root, "h", Json::stringValue))
    {
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if(CheckJsonValueType(root, "name", Json::stringValue))
    {
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }

    if(CheckJsonValueType(root, "time_ms", Json::stringValue))
    {
        m_marqueeViewParam->m_timeMS = QString::fromStdString(root["time_ms"].asString()).toInt();
    }

    if(CheckJsonValueType(root, "startIndex", Json::stringValue))
    {
        m_marqueeViewParam->m_startIndex = QString::fromStdString(root["startIndex"].asString()).toInt();
    }

    if(CheckJsonValueType(root, "endIndex", Json::stringValue))
    {
        m_marqueeViewParam->m_endIndex = QString::fromStdString(root["endIndex"].asString()).toInt();
    }

    if(CheckJsonValueType(root, "positioninfo", Json::stringValue))
    {
        m_marqueeViewParam->m_positionInfo = QString::fromStdString(root["positioninfo"].asString());
    }

    if(CheckJsonValueType(root, "url", Json::stringValue))
    {
        m_marqueeViewParam->m_res = QString::fromStdString(root["url"].asString());
    }
    if (CheckJsonValueType(root, "idtype", Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));
    }
}


void MarqueeView::ParseXML(QDomElement* xmlDomEle)
{
    if(m_marqueeViewParam == NULL)
    {
        m_marqueeViewParam = new MarqueeViewParam;
    }
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name", ""));
    QDomNodeList paramlist = xmlDomEle->childNodes();
    for(int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if(param.isComment()||param.isNull())
        {
            continue;
        }
        int temp = param.attribute("time_ms","-1").toInt();
        if(temp != -1)
        {
             m_marqueeViewParam->m_timeMS = temp;
        }
        int temp1 = param.attribute("startIndex","-1").toInt();
        if(temp1 != -1)
        {
            m_marqueeViewParam->m_startIndex = temp1;
        }
        int temp2 = param.attribute("endIndex","-1").toInt();
        if(temp2 != -1)
        {
            m_marqueeViewParam->m_endIndex = temp2;
        }
        QString tempUrl = param.attribute("positioninfo","");
        if(tempUrl != "")
        {
            m_marqueeViewParam->m_positionInfo = tempUrl;
        }
        QString tempRes = param.attribute("url","");
        if(tempRes != "")
        {
            m_marqueeViewParam->m_res = tempRes;
        }
    }

}

void MarqueeView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type",m_objectParam->GetObjectName());
    dom->setAttribute("zindex", QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid", QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x", QString::number(m_objectParam->GetX()));
    dom->setAttribute("y", QString::number(m_objectParam->GetY()));
    dom->setAttribute("w", QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h", QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name", m_objectParam->GetName());

    QDomElement dom1 = document.createElement("param");
    dom1.setAttribute("time_ms", QString::number(m_marqueeViewParam->m_timeMS));
    dom->appendChild(dom1);

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("positioninfo", m_marqueeViewParam->m_positionInfo);
    dom->appendChild(dom2);

    QDomElement dom3 = document.createElement("param");
    dom3.setAttribute("url", m_marqueeViewParam->m_res);
    dom->appendChild(dom3);

    QDomElement dom4 = document.createElement("param");
    dom4.setAttribute("startIndex", QString::number(m_marqueeViewParam->m_startIndex));
    dom->appendChild(dom4);

    QDomElement dom5 = document.createElement("param");
    dom5.setAttribute("endIndex", QString::number(m_marqueeViewParam->m_endIndex));
    dom->appendChild(dom5);
}

void MarqueeView::TimeOutSlot()
{
    if(m_indexCurrent == -1 )
    {
        m_indexCurrent = m_marqueeViewParam->m_startIndex;
    }

    setGeometry(m_mapPosition[m_indexCurrent].x, m_mapPosition[m_indexCurrent].y,
                m_mapPosition[m_indexCurrent].w, m_mapPosition[m_indexCurrent].h);
    m_label->setFixedSize(size());

    if(m_movie != NULL)
    {
        m_movie->setScaledSize(m_label->size());
        m_movie->start();
        m_label->setMovie(m_movie);
    }
    if(m_marqueeViewParam->m_startIndex == m_marqueeViewParam->m_endIndex)
    {
        if(!m_changeLabelshow)
        {
            m_changeLabelshow = true;
            show();
        }
        else
        {
            m_changeLabelshow = false;
            hide();
        }
        return;
    }

    if(m_marqueeViewParam->m_endIndex == m_indexCurrent)
    {
        m_indexCurrent = m_marqueeViewParam->m_startIndex;
    }
    else
    {
        if(m_marqueeViewParam->m_startIndex>m_marqueeViewParam->m_endIndex)
        {
            m_indexCurrent--;
        }
        else if(m_marqueeViewParam->m_startIndex<m_marqueeViewParam->m_endIndex)
        {
            m_indexCurrent++;
        }
    }
}










